package com.kevin.ymqquan.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

import com.kevin.ymqquan.R;
import com.kevin.ymqquan.adapter.ClubConUserAdapter;
import com.kevin.ymqquan.adapter.ClubUserAdapter;
import com.kevin.ymqquan.application.App;
import com.kevin.ymqquan.bean.ClubConUser;
import com.kevin.ymqquan.constants.Constants;
import com.kevin.ymqquan.custom.CustomToast;
import com.kevin.ymqquan.httppost.Helper;
import com.kevin.ymqquan.httppost.HttpPostService;
import com.kevin.ymqquan.view.CommonListView;
import com.kevin.ymqquan.view.CommonListView.IXListViewListener;

public class ClubConUserActivity extends Activity implements
		IXListViewListener, OnItemClickListener, OnItemSelectedListener {

	//test 
	
	private ImageView iv_club_user_back;
	private EditText et_search_name;
	private TextView tv_user_search_button;
	private TextView tv_club_detail_title;
	private App application;
	private boolean isRefresh = false;
	private Dialog dialog;
	private String activeId;
	private String clubId;
	private Spinner sp_sex;
	private List<String> infoList = new ArrayList<String>();
	private ArrayAdapter<String> adapter;

	private String userSex = "";

	private List<ClubConUser> clubUserList = new ArrayList<ClubConUser>();
	private int currPage = 1;

	private CommonListView lv_club_user_list;

	ClubConUserAdapter clubConUserAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_club_user);
		init();

		Intent i = getIntent();
		activeId = i.getStringExtra("activeId");
		clubId = i.getStringExtra("clubId");
		if (Helper.checkConnection(ClubConUserActivity.this)) {
			dialog = CustomToast.createLoadingDialog(ClubConUserActivity.this,
					"数据获取中...");
			dialog.setCancelable(true);
			dialog.show();
			ActiveAsynTask policyTask = new ActiveAsynTask(true);
			policyTask.execute();

		} else {
			CustomToast.CustomActivityToast(ClubConUserActivity.this,
					"网络连接异常，请检查您的网络", -80);
		}

	}

	private void init() {
		application = (App) getApplication();
		infoList.add("全部");
		infoList.add("男");
		infoList.add("女");
		sp_sex = (Spinner) findViewById(R.id.spinner_sex);
		adapter = new ArrayAdapter<String>(this, R.layout.free_spinner_text,
				infoList);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		sp_sex.setAdapter(adapter);
		lv_club_user_list = (CommonListView) findViewById(R.id.lv_club_user_list);
		iv_club_user_back = (ImageView) findViewById(R.id.iv_club_user_back);

		et_search_name = (EditText) findViewById(R.id.et_leaguer_search);
		tv_user_search_button = (TextView) findViewById(R.id.tv_leaguer_search_button);
		tv_club_detail_title = (TextView) findViewById(R.id.tv_club_detail_title);
		tv_club_detail_title.setText("消费管理");

		tv_user_search_button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				onRefresh();

			}
		});

		// 下拉刷新不可用
		lv_club_user_list.setPullLoadEnable(true);
		lv_club_user_list.setPullRefreshEnable(true);
		lv_club_user_list.setXListViewListener(this);
		lv_club_user_list.stopLoadMore();
		lv_club_user_list.stopRefresh();

		clubConUserAdapter = new ClubConUserAdapter(ClubConUserActivity.this,
				clubUserList);
		lv_club_user_list.setAdapter(clubConUserAdapter);
		lv_club_user_list.setOnItemClickListener(ClubConUserActivity.this);

		iv_club_user_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub\
				ClubConUserActivity.this.finish();
			}
		});

	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		currPage = 1;
		isRefresh = true;
		ActiveAsynTask policyTask = new ActiveAsynTask(false);
		policyTask.execute();
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		isRefresh = false;
		++currPage;
		ActiveAsynTask policyTask = new ActiveAsynTask(false);
		policyTask.execute();

	}

	public void clearList() {
		currPage = 1;
		clubUserList.clear();
		clubConUserAdapter.notifyDataSetChanged();

	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		// TODO Auto-generated method stub

		if (position != 0) {
			position--;
			if (Float.parseFloat(clubUserList.get(position).getConsume()) > 0) {
				CustomToast.CustomActivityToast(ClubConUserActivity.this,
						"该用户已经消费过！", -80);
				return;
			} else {
				Intent i = new Intent(ClubConUserActivity.this,
						ConDetailActivity.class);

				i.putExtra("Ids", clubUserList.get(position).getIds() + "");
				i.putExtra("clubId", clubId);
				i.putExtra("activeId", activeId);

				// startActivityForResult(i, position);
				startActivityForResult(i, position);
				// startActivity(i);
			}

		}
		// Log.i("kevinlog", "----" + position);

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		// super.onActivityResult(requestCode, resultCode, data);
		clubUserList.get(requestCode)
				.setConsume(data.getStringExtra("consume"));
		clubConUserAdapter.notifyDataSetChanged();
		// Log.i("kevinlog", requestCode + "----" + resultCode);
	}

	class ActiveAsynTask extends AsyncTask<String, Object, String> {

		private boolean dialogShow = true;

		public ActiveAsynTask(boolean dialogShow) {
			// TODO Auto-generated constructor stub
			this.dialogShow = dialogShow;
		}

		@Override
		protected String doInBackground(String... params) {

			String param = "{\"method\":\"clubUserConList\",\"pageNum\":\""
					+ currPage + "\",\"activeId\":\"" + activeId
					+ "\",\"name\":\"" + et_search_name.getText().toString()
					+ "\",\"sex\":\"" + userSex + "\"}";

			String replyList = "";
			try {
				replyList = HttpPostService.PostJsonString(
						Constants.ServerAddr, param);
			} catch (Exception e) {
				e.printStackTrace();
			}
			// Log.i("kevinlog", "--++--" + param);
			// Log.i("kevinlog", "--++--" + replyList);
			return replyList;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		@Override
		protected void onPostExecute(String JsonResult) {
			// TODO Auto-generated method stub
			super.onPostExecute(JsonResult);
			// Log.i("sssss", JsonResult);
			if (isRefresh) {
				clearList();
			}
			if (JsonResult != null) {
				// String result = JsonResult.replace("\n", "");
				String result = JsonResult;
				JSONObject jsonObject;
				try {

					jsonObject = new JSONObject(result);
					String resultType = jsonObject.getString("status");
					if ("0".equals(resultType)) {
						JSONArray jsonArray = jsonObject
								.getJSONArray("clubUserConList");

						for (int i = 0; i < jsonArray.length(); i++) {
							JSONObject eduPolicyObject = jsonArray
									.getJSONObject(i);
							ClubConUser list = new ClubConUser();
							list.setConsume(eduPolicyObject
									.getString("consume"));
							list.setUserName(eduPolicyObject
									.getString("userName"));
							list.setYearcard(eduPolicyObject
									.getString("yearcard"));
							list.setBalancecard(eduPolicyObject
									.getString("balancecard"));
							list.setYeartimescard(eduPolicyObject
									.getString("yeartimescard"));

							list.setIds(eduPolicyObject.getString("Ids"));
							clubUserList.add(list);
						}

						// Log.i("kevinlog", "--++--" +
						// clubUserList.size()+"size");
						sp_sex.setOnItemSelectedListener(ClubConUserActivity.this);
						clubConUserAdapter.notifyDataSetChanged();
						if (dialogShow) {
							dialog.dismiss();
						}
					} else {
						if (dialogShow) {
							dialog.dismiss();
						}
						CustomToast.CustomActivityToast(
								ClubConUserActivity.this, "没有更多了", -80);
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					if (dialogShow) {
						dialog.dismiss();
					}
					CustomToast.CustomActivityToast(ClubConUserActivity.this,
							"没有更多了", -80);
					e.printStackTrace();
				}
				lv_club_user_list.stopLoadMore();
				lv_club_user_list.stopRefresh();
			} else {
				if (dialogShow) {
					dialog.dismiss();
				}
				CustomToast.CustomActivityToast(ClubConUserActivity.this,
						"网络异常请稍后重试！", -80);

			}
		}
	}

	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) {
		// TODO Auto-generated method stub
		// Log.i("kevinlog", arg2 + "");
		if (arg2 == 0) {
			userSex = "";
		} else {
			userSex = arg2 + "";
		}

		onRefresh();
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub

	}

}
